package com.study.talk.app.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationBarView;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.study.talk.R;
import com.study.talk.app.App;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.friend.AddFriendActivity;
import com.study.talk.app.group.AddGroupActivity;
import com.study.talk.app.group.CreateGroupActivity;
import com.study.talk.app.group.GroupNoticeActivity;
import com.study.talk.app.other.NewFriendActivity;
import com.study.talk.app.self.UserInfoSelfActivity;
import com.study.talk.databinding.ActivityHomeBinding;
import com.study.talk.entity.Message;
import com.study.talk.entity.resp.MessageTypeResponse;
import com.study.talk.app.home.fragment.ContactsFragment;
import com.study.talk.app.home.fragment.HomeFragment;
import com.study.talk.app.home.fragment.OtherFragment;
import com.study.talk.netty.message.TalkMessage;
import com.study.talk.netty.message.code.MessageCode;
import com.study.talk.util.EventBusUtil;
import com.study.talk.net.OkHttp;
import com.study.talk.util.GsonInstance;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends BaseActivity {


    private ActivityHomeBinding activityMainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());

        setSupportActionBar(activityMainBinding.appBarMain.mainToolbar);

        initView();

        activityMainBinding.appBarMain.mainToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                if (activityMainBinding.drawerLayout.isDrawerOpen(Gravity.START)) {
                    activityMainBinding.drawerLayout.closeDrawer(Gravity.START);
                } else {
                    activityMainBinding.drawerLayout.openDrawer(Gravity.START);
                }
            }
        });
        activityMainBinding.appBarMain.mainNav.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.home_nav_home: {
                        replace(new HomeFragment());
                        break;
                    }
                    case R.id.home_nav_contacts: {
                        replace(new ContactsFragment());
                        break;
                    }
                    case R.id.home_nav_other: {
                        replace(new OtherFragment());
                        break;
                    }
                }
                return true;
            }
        });
        activityMainBinding.leftNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.left_menu_new_friend ->
                            startActivity(new Intent(HomeActivity.this, NewFriendActivity.class));
                    case R.id.left_menu_group_info ->
                            startActivity(new Intent(HomeActivity.this, GroupNoticeActivity.class));
                    case R.id.left_menu_exit -> new AlertDialog.Builder(HomeActivity.this)
                            .setTitle("退出登录提醒")
                            .setMessage("所有的聊天信息都会被清空，您确定要退出吗？")
                            .setNegativeButton("确定", (dialog, i) -> {
                                getApp().logout();
                                dialog.dismiss();
                                finish();
                            }).setPositiveButton("取消", ((dialog, i) -> dialog.dismiss()))
                            .show();
                }
                return true;
            }
        });
        replace(new HomeFragment());
    }

    @Override
    protected void onStart() {
        super.onStart();
        //加载缓存在服务器的未读消息
        if (getApp().loadCache) {
            getApp().loadCache = false;
            OkHttp.get("/message/list/" + getApp().userId(), res -> {
                Gson gson = GsonInstance.instance;
                MessageTypeResponse response = gson.fromJson(res, MessageTypeResponse.class);
                List<TalkMessage> newList = new ArrayList<>();
                for (Message message : response.getData()) {
                    Class<? extends TalkMessage> type = MessageCode.getMessageByMessageType(message.getType().byteValue());
                    TalkMessage talkMessage = gson.fromJson(message.getMessage(), type);
                    newList.add(talkMessage);
                }
                runOnUiThread(() -> {
                    for (TalkMessage message : newList) {
                        EventBusUtil.sendEvent(message);
                    }
                });
            });
        }
    }

    public void replace(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.main_fragment, fragment);
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_menu_add_friend ->
                    startActivity(new Intent(this, AddFriendActivity.class));
            case R.id.main_menu_add_group ->
                    startActivity(new Intent(this, AddGroupActivity.class));
            case R.id.main_menu_create_group ->
                    startActivity(new Intent(this, CreateGroupActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        View headerView = activityMainBinding.leftNavView.getHeaderView(0);
        headerView.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserInfoSelfActivity.class);
            intent.putExtra("userId", getApp().userId());
            startActivity(intent);
        });
        ImageView accountHeadImg = headerView.findViewById(R.id.account_head_img);
        TextView accountUsername = headerView.findViewById(R.id.account_username);
        TextView accountIntroduce = headerView.findViewById(R.id.account_introduce);
        App app = getApp();
        Glide.with(HomeActivity.this).load(OkHttp.URL + app.userInfo.getAvatar()).into(accountHeadImg);
        accountUsername.setText(app.userInfo.getNickName());
        accountIntroduce.setText(app.userInfo.getIntroduce());
    }

}